package com.anxuan.agent.demo.invoke;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 使用Hutool实现阿里云灵机API调用
 */
public class HttpAiInvoke {
    
    private static final String API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
    
    public static String callWithMessage() {
        // 构建消息
        List<Map<String, String>> messages = new ArrayList<>();
        
        Map<String, String> systemMsg = new HashMap<>();
        systemMsg.put("role", "system");
        systemMsg.put("content", "You are a helpful assistant.");
        
        Map<String, String> userMsg = new HashMap<>();
        userMsg.put("role", "user");
        userMsg.put("content", "你是谁？");
        
        messages.add(systemMsg);
        messages.add(userMsg);
        
        // 构建参数
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("result_format", "message");
        
        // 构建输入
        Map<String, Object> input = new HashMap<>();
        input.put("messages", messages);
        
        // 构建请求体
        JSONObject requestBody = JSONUtil.createObj()
                .set("model", "qwen-plus")
                .set("input", input)
                .set("parameters", parameters);
        
        // 发送请求
        HttpResponse response = HttpRequest.post(API_URL)
                .header("Authorization", "Bearer " + TestApiKey.API_KEY)
                .header("Content-Type", "application/json")
                .body(requestBody.toString())
                .execute();
        
        return response.body();
    }
    
    public static void main(String[] args) {
        try {
            String result = callWithMessage();
            System.out.println(result);
        } catch (Exception e) {
            System.err.println("An error occurred while calling the generation service: " + e.getMessage());
        }
        System.exit(0);
    }
}